package cfengMiddleware.server.rabbitmq.producer;

import cfengMiddleware.server.rabbitmq.entity.MessageEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/9/18
 * 创建rabbitMQ死信队列生产者
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class DeadProducer {

    private final ObjectMapper objectMapper;

    private final RabbitTemplate rabbitTemplate;

    private final Environment environment;

    public void sendDeadMessage(MessageEntity messageEntity) {
        try {
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            //指定路由的交换机和routing key
            rabbitTemplate.setExchange(Objects.requireNonNull(environment.getProperty("spring.rabbitmq.exchange-basic-name")));
            rabbitTemplate.setRoutingKey(Objects.requireNonNull(environment.getProperty("spring.rabbitmq.route-basic-name")));
            //将消息发送到死信队列
            rabbitTemplate.convertAndSend(messageEntity,message -> {
                MessageProperties properties = message.getMessageProperties();
                properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                properties.setHeader(AbstractJavaTypeMapper.DEFAULT_KEY_CLASSID_FIELD_NAME,MessageEntity.class);
                //同时设置TTL，以较短的为准，在配置时设置的死信队列TTL 10s
                properties.setExpiration(String.valueOf(10000));
                return message;
            });
            log.info("死信队列消息模型，消息发送成功： {}",messageEntity);
        } catch (Exception e) {
            log.error("死信对垒模型： 消息发送异常： {}",messageEntity,e.fillInStackTrace());
        }
    }
}
